/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mx.saco.dao.impl;


import com.mx.saco.dao.GeneralDAO;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 */
public abstract class GeneralDAOImpl<T, ID extends Serializable> implements GeneralDAO<T, ID> {

    @PersistenceContext(unitName = "finanzaSacoPU")
    protected EntityManager em;
    protected Class<T> tipoEntidad;

    @SuppressWarnings("unchecked")
    protected GeneralDAOImpl() {
        Class<T> class1 = (Class<T>) ((ParameterizedType) getClass().
                getGenericSuperclass()).getActualTypeArguments()[0];
        this.tipoEntidad = class1;
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void guardar(T entidad) {
        em.persist(entidad);
        em.flush();
        
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRED)
    public void actualizar(T entidad) {
        em.merge(entidad);
        em.flush();
    }

    @Override
    public void borrar(T entidad) {      
        em.remove(entidad);
    }

    @Override
    public T buscarPorId(ID id) {
        return em.find(tipoEntidad, id);
    }

    @Override
    public List<T> buscarTodo() {
        List<T> entidades;
        Query query = em.createQuery("SELECT e FROM " + tipoEntidad.getSimpleName() + " e ");
        entidades = query.getResultList();
        return entidades;
    }

    @Override
    public void refrescar(T entidad) {
        em.refresh(entidad);
    }

    public EntityManager getEm() {
        return em;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }
}
